﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

//using DevExpress.LocalizationCHS;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraTreeList;
//using JOrder.Data;
using DevExpress.XtraGrid.Columns;
using JsalesModel;

namespace JSales.ModuleSystem
{
    public partial class DeptForm : Form
    {
        public DeptForm()
        {
            InitializeComponent();
        }

        BindingSource bindDept=new BindingSource();

        private string status = null;

         private void DeptFormLoad(object sender, EventArgs e)
        {
            using (var dbConText = new JYEntities())
            {
                IQueryable<JsalesModel.TbDept> dept = dbConText.TbDepts;
                if (dept.Any())
                {
                    bindDept.DataSource = dept;
                    treeList1.DataSource = bindDept;
                    
                    treeList1.PopulateColumns();
                    treeList1.BestFitColumns();
                    ////treeList1 列设置
                    treeList1.Columns["DeptName"].FieldName = "DeptName";
                    treeList1.Columns["DeptName"].Caption = "部门";
                    treeList1.Columns["DeptName"].Name = "DeptName";

                    RepositoryItemCheckEdit check = new RepositoryItemCheckEdit();
                    check.ValueChecked = true;
                    check.ValueUnchecked = false;
                    treeList1.Columns["Isdeleted"].ColumnEdit = check;
                    treeList1.Columns["Isdeleted"].FieldName = "Isdeleted";
                    treeList1.Columns["Isdeleted"].Caption = @"是否已删除";

                    treeList1.Columns["Isdeleted"].Visible = true;
                    treeList1.Columns["LastEditDate"].Visible = false;
                    treeList1.Columns["CreationDate"].Visible = false;
                    treeList1.Columns["VLeft"].Visible = false;
                    treeList1.Columns["VRight"].Visible = false;

                    treeList1.KeyFieldName = "DeptID";
                    treeList1.ParentFieldName = "UpDept";
                    treeList1.OptionsView.ShowRoot = true;
                    //treeList1.OptionsView.ShowCheckBoxes = true; //显示check框
                    treeList1.OptionsView.ShowHorzLines = true;
                    treeList1.OptionsView.ShowVertLines = true;
                    treeList1.ExpandAll();                      //全部展开
                    treeList1.OptionsBehavior.Editable = false; //不可编辑

                    treeList1.LookAndFeel.UseDefaultLookAndFeel = false;
                    treeList1.LookAndFeel.UseWindowsXPTheme = true;

                    lookUpEdit1.Properties.DataSource = bindDept;
                    lookUpEdit1.Properties.PopulateColumns();

                    lookUpEdit1.Properties.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
                    lookUpEdit1.Properties.DisplayMember = "DeptName";
                    lookUpEdit1.Properties.ValueMember = "DeptID";

                    lookUpEdit1.Properties.Columns["DeptID"].Visible = false;
                    lookUpEdit1.Properties.Columns["Isdeleted"].Visible = false;
                    lookUpEdit1.Properties.Columns["LastEditDate"].Visible = false;
                    lookUpEdit1.Properties.Columns["CreationDate"].Visible = false;
                    //lookUpEdit1.Properties.Columns["TbUsers"].Visible = false;
                    lookUpEdit1.Properties.Columns["UpDept"].Visible = false;
                    lookUpEdit1.Properties.Columns["DeptName"].Caption = "部门";

                    textDept.Enabled = false;
                    lookUpEdit1.Enabled = false;
                    barButtonSave.Enabled = false;
                    barButtonCancel.Enabled = false;
                }
            } 
             
        }

         
        /// <summary>
        /// treelist控件单击事件
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">e</param>
         private void treeList1_MouseDown(object sender, MouseEventArgs e)
         {
             TreeListHitInfo hit = new TreeListHitInfo();
             hit = treeList1.CalcHitInfo(e.Location);

             if(hit.HitInfoType!=HitInfoType.Cell)
             {
                 return; 
             }
             if (e.Button==MouseButtons.Right)
             {
                 return; 
             }
             //MessageBox.Show(hit.Node.GetValue("DeptID").ToString());
             textID.Text=hit.Node.GetValue("DeptID").ToString();
             textDept.Text = hit.Node.GetValue("DeptName").ToString();
             lookUpEdit1.EditValue = int.Parse(hit.Node.GetValue("UpDept").ToString()); //值类型不一致，会导致lookupEdit内容不会联动。

             
         }


        #region 先根遍历算法生成部门结构
        private int right;
        private int ReBuildTree(int root,int left)
        {
            right = left + 1;
            var dbConText = new JYEntities();
            IQueryable<TbDept> childs = from i in dbConText.TbDepts
                                        where i.UpDept == root
                                        select i;
            int row = 0;
            while (childs!=null&&childs.Any()&&row <childs.Count())
            {
                right = ReBuildTree(childs.ElementAt(row).DeptID, right);
                row += 1;
            }
            UpdateDept(root, left, right);
            return right + 1;
        }        
        
        private void UpdateDept(int deptid,int vleft,int vright)
        {
            var dbConText = new JYEntities();
            IQueryable<TbDept> childs = from i in dbConText.TbDepts
                                        where i.DeptID == deptid
                                        select i;
            if (childs.Any())
            {
                TbDept dept = childs.FirstOrDefault();            
                dept.VLeft = vleft;
                dept.VRight = vright;
                dbConText.SaveChanges();
            }
        }
        #endregion

        private void barButtonCreate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            textDept.Enabled = true;
            textDept.Text = null;
            lookUpEdit1.Enabled = true;
            lookUpEdit1.EditValue = null;
            barButtonCreate.Enabled = false;
            barButtonEdit.Enabled = false;
            barButtonDelete.Enabled = false;
            barButtonSave.Enabled = true;
            barButtonCancel.Enabled = true;
            treeList1.Enabled = false;
            status = "insert";
        }

        private void barButtonEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            textDept.Enabled = true;
            //textDept.Text = null;
            lookUpEdit1.Enabled = true;
            lookUpEdit1.EditValue = null;
            barButtonCreate.Enabled = false;
            barButtonEdit.Enabled = false;
            barButtonDelete.Enabled = false;
            barButtonSave.Enabled = true;
            barButtonCancel.Enabled = true;
            treeList1.Enabled = true;
            status = "edit";    
        }

        private void barButtonSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var dbConText = new JYEntities();
            switch (status)
            {
                case "insert":
                    {
                        if (textDept.Text.Equals(""))
                        {
                            MessageBox.Show("请输入部门名称");
                            textDept.Focus();
                        }
                        else if (lookUpEdit1.EditValue == null || lookUpEdit1.EditValue.Equals("") || lookUpEdit1.EditValue.Equals("选择上级部门"))
                        {
                            MessageBox.Show("请选择上级部门");
                            lookUpEdit1.Focus();
                        }
                        else
                        {
                            TbDept dept = new TbDept();
                            dept.DeptName = textDept.Text;
                            dept.UpDept = int.Parse(lookUpEdit1.EditValue.ToString());
                            dept.Isdeleted = false;
                            dept.CreationDate = DateTime.Now;
                            dbConText.Add(dept);
                            dbConText.SaveChanges();
                            //GlobalVar.SelectDept();
                            //ReBuildTree(1, 1);
                            this.DeptFormLoad(sender, e);
                        }
                        barButtonCancel_ItemClick(sender, e);
                    }
                    break;
                case "edit":
                    {
                        if (textDept.Text.Equals(""))
                        {
                            MessageBox.Show("请输入部门名称");
                            textDept.Focus();
                        }
                        else if (lookUpEdit1.EditValue == null || lookUpEdit1.EditValue.Equals("") || lookUpEdit1.EditValue.Equals("选择上级部门"))
                        {
                            MessageBox.Show("请选择上级部门");
                            lookUpEdit1.Focus();
                        }
                        else
                        {
                            TbDept dept = (from d in dbConText.TbDepts
                                           where d.DeptID == Convert.ToInt32(textID.Text)
                                           select d).FirstOrDefault();
                            dept.DeptID = int.Parse(textID.Text);
                            dept.DeptName = textDept.Text;
                            dept.UpDept = int.Parse(lookUpEdit1.EditValue.ToString());
                            dept.Isdeleted = false;
                            dept.LastEditDate = DateTime.Now;
                            dbConText.SaveChanges();
                            //BuildTree(1, 1);
                            this.DeptFormLoad(sender, e);
                        }
                        if (status == null)
                        {
                            MessageBox.Show("未对部门做任何修改");
                        }
                        barButtonCancel_ItemClick(sender, e);
                    }
                    break;
            }
        }

        private void barButtonCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            textDept.Enabled = false;
            lookUpEdit1.Enabled = false;
            barButtonCreate.Enabled = true;
            barButtonEdit.Enabled = true;
            barButtonDelete.Enabled = true;
            barButtonSave.Enabled = false;
            barButtonCancel.Enabled = false;
            treeList1.Enabled = true;
            status = null;
        }

        private void barButtonDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var dbConText = new JYEntities();
            if (textID.Text.ToString().Equals(""))
            {
                MessageBox.Show("请先选择部门");
            }
            else
            {
                if (MessageBox.Show("确认删除此部门？", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    TbDept dept = (from d in dbConText.TbDepts
                                   where d.DeptID == Convert.ToInt32(textID.Text)
                                   select d).FirstOrDefault();
                    dept.Isdeleted = true;
                    dbConText.SaveChanges();

                    this.DeptFormLoad(sender, e);
                    //treeList1.DeleteNode(treeList1.FocusedNode);
                }
                else
                {
                    barButtonCancel_ItemClick(sender, e);
                }
            }
        }

        private void barButtonRestore_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var dbConText = new JYEntities();
            if (textID.Text.ToString().Equals(""))
            {
                MessageBox.Show("请先选择部门");
            }
            else
            {
                if (MessageBox.Show("确认还原此部门？", "还原确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    TbDept dept = (from d in dbConText.TbDepts
                                   where d.DeptID == Convert.ToInt32(textID.Text)
                                   select d).FirstOrDefault();
                    dept.Isdeleted = false;
                    dbConText.SaveChanges();

                    this.DeptFormLoad(sender, e);
                    //treeList1.DeleteNode(treeList1.FocusedNode);
                }
                else
                {
                    barButtonCancel_ItemClick(sender, e);
                }
            }
        }

        private void barButtonRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ReBuildTree(1, 1);
            MessageBox.Show("刷新完成！");
        }
    }
}
